#!/usr/bin/env bash

# shellcheck disable=SC2016

# 输出粉色文本
out_pink() {
    echo -e "\033[35m$1\033[0m"
}

# 输出青色文本
out_cyan() {
    echo -e "\033[36m$1\033[0m"
}

timestamp() {
    curl -sSL -X 'POST' 'https://blink.bilibili.co/api/v1/blink/login/timestamp' \
        -H 'Accept: application/json, text/plain, */*' \
        -H 'Content-Type: application/json; charset=UTF-8' \
        -d '{}' | jq --raw-output '.data'
    # {"code":200,"message":"","data":"CNtNmEUCs****** 获取时间戳加密
}

{
    _file_path="/data/mcdn/config.json"
    [ ! -f "$_file_path" ] && out_red "[ERROR]配置不存在: $_file_path" && exit 1

    _json="$(awk 'NF' $_file_path)"
}

{
    _timestamp="$(timestamp)"

    # 标记加密算法：用户名+密码sha256+时间戳加密
    _marks="$(echo -n "bdwlac9630b8b84cc3d096b6f97501409976d5653ba16190e958749891f191b7f7d3$_timestamp" | sha256sum | awk '{print $1}')"

    # 参数为空退出脚本
    [[ -z "$_timestamp" || -z "$_marks" ]] && exit 1

    _submit_data='{"name":"bdwl","password":"ac9630b8b84cc3d096b6f97501409976d5653ba16190e958749891f191b7f7d3","timestamp":"'"$_timestamp"'","marks":"'"$_marks"'"}'

    curl -sSL -X 'POST' 'https://blink.bilibili.co/api/v1/blink/login' \
        -H 'Accept: application/json, text/plain, */*' \
        -H 'Content-Type: application/json; charset=UTF-8' \
        -c /data/mcdn/cookie.txt \
        -d "$_submit_data" | jq

    # {"code":200,"message":"登录成功","data":null}
}

# =============================
# 退出登录，需要使用cookie中的 token=xxx
# =============================
loginout() {
    curl -sSL -X 'POST' 'https://blink.bilibili.co/api/v1/blink/outLogin' \
        -H 'Accept: application/json, text/plain, */*' \
        -H 'Content-Type: application/json; charset=UTF-8' \
        -b /data/mcdn/cookie.txt \
        -d '{}' &>/dev/null

    # {"code":200,"message":"登出成功","data":null}
}

main() {

    out_pink "============= 提交配置 ============="

    # 开始提交
    curl -sSL -X 'POST' 'https://blink.bilibili.co/api/v1/blink/proxy' \
        -H 'Accept: application/json, text/plain, */*' \
        -H 'Content-Type: application/json; charset=UTF-8' \
        -b /data/mcdn/cookie.txt \
        -d "$_json" | jq

    loginout
}
main

: <<!

    bash -c "$(curl -sSL https://gitea.kuaicdn.cn/Reverse/work-script/raw/branch/main/idc/app/blink/submit.sh)"

!